package com.petadoption.serverclient.controller;

import com.petadoption.serverclient.entity.Car;
import com.petadoption.serverclient.entity.User;
import com.petadoption.serverclient.service.ICarService;
import com.petadoption.serverclient.utils.Result;
import com.petadoption.serverclient.utils.TokenUtil;
import com.petadoption.serverclient.vo.CarVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/car")
public class CarController {

    @Resource
    private Result result;
    @Resource
    private ICarService carService;

    //修改商品数量
    @PostMapping("/updateCount")
    public Result updateCount(@RequestBody Car car) {
        Car car1 = carService.findCar(car.getCarId());
        if (car1 == null) return result.fail("修改失败");
        int carCount1 = car1.getCarCount();
        if (1 == car.getCarCount()) {
            carCount1++;
        } else {
            carCount1--;
        }
        car1.setCarCount(carCount1);
        int i = carService.updateCarCount(car1);
        if (i > 0) return result.success("修改成功", carCount1);
        return result.fail("修改失败");
    }

    //添加购物车
    @PostMapping("/addCarProduct")
    public Result addCarProduct(@RequestBody Car car) {
        car.setCarUser(TokenUtil.getCurrenUser().getUserId());
        int i = carService.addCarProduct(car);
        if (i < 0) return result.fail("商品添加购物车失败");
        return result.success("商品添加购物车成功");
    }


    //查询所有购物车商品
    @GetMapping("/all")
    public Result findAll() {
        User user = TokenUtil.getCurrenUser();
        List<CarVO> list = carService.findAll(user.getUserId());
        if (list.isEmpty()) return result.fail("暂无商品");
        return result.success("购物车商品", list);
    }

    //删除商品
    @GetMapping("/del/{carId}")
    public Result findAll(@PathVariable Integer carId) {
        int i = carService.delCar(carId);
        if (i < 0) return result.fail("删除失败");
        return result.success("删除成功");
    }

}
